'use strict'
import axios from 'axios'
import Util from '../../utils'
import cache from '../../utils/cache'

const axiosInstance = axios.create({
  timeout: 200000
})

// Axios拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    config.timeout = 200000
    config.withCredentials = true
    if (config.headers['Content-Type'] === undefined) {
      config.headers['Content-Type'] = 'application/json'
      // json -> form data
      config['transformRequest'] = [
        (data) => {
          return Util.jsonToString(data)
        }
      ]
    }
    const tokenCache = cache.get('token')
    if (tokenCache) {
      config.headers['X-Auth-Token'] = tokenCache.value
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

axiosInstance.interceptors.response.use(
  (response) => {
    if (response.status < 300) {
      return Object.assign({ success: true }, response)
    } else {
      return Object.assign({ success: false }, response)
    }
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          console.log('axios result:401')
          break
        case 404:
          console.log('axios result:404')
          break
        case 504:
          console.log('axios result:504')
          break
        default:
          break
      }
    }
    Object.assign(error.response, { message: '系统异常！', success: false })
    return error.response
  }
)
export default axiosInstance
